﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;

namespace MH3GAPP.Common
{
    class DbManager
    {
        #region var
        private static DbManager instance;
        private static object locker = new object();

        private static OleDbConnection m_oleConnection = null;
        private bool m_isInit = false;
        #endregion

        #region Constructor
        private DbManager()
        {
        }
        #endregion

        #region Destructor
        ~DbManager()
        {
        }
        #endregion

        #region GetInstance
        public static DbManager GetInstance()
        {
            if (instance == null)
            {
                lock (locker)
                {
                    if (instance == null)
                    {
                        instance = new DbManager();
                    }
                }
            }
            return instance;
        }
        #endregion

        #region 初始化
        public void Init()
        {
            if (!m_isInit) {
                try
                {
                    string executePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    string strConnection = @"Provider = Microsoft.ACE.OLEDB.12.0;";
                    strConnection += @"Data Source = " + executePath + @"\000.accdb";
                    m_oleConnection = new OleDbConnection(strConnection);

                    m_isInit = true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
        }
        #endregion

        #region 获取ole连接
        public OleDbConnection GetOleConection()
        {
            if (m_oleConnection == null) {
                Init();
            }

            if (m_oleConnection.State != ConnectionState.Open)
            {
                m_oleConnection.Open();
            }
            return m_oleConnection;
        }
        #endregion

        #region 关闭数据库
        public void CloseDb()
        {
            ErrorLogHelper error = new ErrorLogHelper();
            try
            {
                if (m_oleConnection.State == ConnectionState.Open)
                {
                    m_oleConnection.Close();
                }

                m_oleConnection = null;
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show("关闭数据库异常！\n" + ex.Message.ToString());
                error.Log(ex.Message.ToString());
            }
        }
        #endregion
    }
}
